package edu.sysu.demo.petrabbit.config;

import com.google.common.io.BaseEncoding;
import edu.sysu.demo.petrabbit.Publisher;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.math3.random.MersenneTwister;
import org.apache.commons.math3.random.RandomAdaptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

@Slf4j
@Configuration
public class SchedulingConfig {

  private Publisher publisher;

  private BaseEncoding baseEncoding;

  private ThreadLocal<Random> random = ThreadLocal.withInitial(
      () -> new RandomAdaptor(new MersenneTwister()));

  @Scheduled(fixedRate = 10 * 1_000)
  public void send() {
    byte[] bytes = new byte[16];
    random.get().nextBytes(bytes);
    publisher.send(bytes);
    log.info("Message {} sent at : {}",
        baseEncoding.encode(bytes),
        LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME));
  }

  @Autowired
  public void setPublisher(Publisher publisher) {
    this.publisher = publisher;
  }

  @Autowired
  public void setBaseEncoding(BaseEncoding baseEncoding) {
    this.baseEncoding = baseEncoding;
  }
}
